<?php

namespace App\Exceptions;

use App\Library\MySeasLog;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var string[]
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var string[]
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e): Response|JsonResponse|\Symfony\Component\HttpFoundation\Response
    {
        if ($request->input('syp_viki')) {
            return parent::render($request, $e);
        } else if ($e instanceof ValidationException) {
            $errors = $e->validator->errors()->toArray();
            if (count($errors)) {
                MySeasLog::error($errors);
                return failCodeMessage(422, $errors[array_keys($errors)[0]][0]);
            }
        } else if ($e instanceof QueryException) {
            MySeasLog::error([423, $e->getMessage()]);
            return failCodeMessage(423, $e->getMessage());
        } else if ($e instanceof ModelNotFoundException) {
            MySeasLog::error([424, $e->getMessage()]);
            return failCodeMessage(424, $e->getMessage());
        } else if ($e instanceof NotFoundHttpException) {
            MySeasLog::error([404, '找不到页面']);
            return fail(404);
        } else if ($e instanceof Exception) {
            if ($request->input('syp_viki')) {
                MySeasLog::error([499, $e->getMessage()]);
                return failCodeMessage(499, $e->getMessage());
            }
            MySeasLog::error([$e->getMessage()]);
            return failMessage($e->getMessage());
        }
        return parent::render($request, $e);
    }
}
